<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>图片水印</title>
  <style>
    * {
      margin: 0;
      padding: 0;
    }
    body {
      background-color: gainsboro;
    }
      #content {
        margin: 0 auto;
        width: 1024px;
        background-color:burlywood;
      }
      img {
        width: 100%;
        height: 100%;
      }
  </style>
</head>

<body>

  <div id="content">
    <img id="resultImage">
  </div>

  <script>
  // 查定图片
  let asseImage
  let coditionCode1Image
  let coditionCode2Image
  let coditionCode3Image
  let optionChoicedImage

  let canvas = document.createElement('canvas');
  let ctx

  async function draw() {
    
   await this.renderImage().then(() => {
      // 根据图片设置画布宽高
      canvas.width = asseImage.width
      canvas.height = asseImage.height
      ctx = canvas.getContext('2d')
      // 查定表模板
      ctx.drawImage(asseImage, 0, 0, asseImage.width, asseImage.height);
      
      ctx.font = "24px serif";
      // 姓名
      ctx.fillText("孙杰", 300, 492)

      let x = 18 + 628 * 0.420 - 10
      let y = 1204 + 420 * 0.124 - 10
      ctx.drawImage(coditionCode1Image, x, y, 20, 20)

      ctx.drawImage(optionChoicedImage, 223, 1900, 32, 32)
    })

    console.log("over");  
    convertCanvasToImage(canvas)
  }

 function renderImage() {
    const that = this
    // 这里使用promise.all(),不懂得可以百度一下，传入的是一个promise数组队列，这里就是加载完成的图片
    // 这个地方可以有更优雅的写法
    return Promise.all([
      // 加载模板图片
      this.loadImage("./imgs/assese_printer.jpeg", (img) => {
        asseImage = img
      }),
      this.loadImage("./imgs/codition_code_1.png", (img) => {
        coditionCode1Image = img
      }),
      this.loadImage("./imgs/codition_code_2.png", (img) => {
        coditionCode2Image = img
      }),
      this.loadImage("./imgs/codition_code_3.png", (img) => {
        coditionCode3Image = img
      }),
      this.loadImage("./imgs/option_choiced.png", (img) => {
        optionChoicedImage = img
      }),
    ])
  }

  // 预加载图片，最后返回一个promise对象
  function loadImage(url, callback) {
    return new Promise((resolve) => {
      const img = new Image();
      img.onload = () => {
        // 闭包回调图片
        callback(img)
        resolve()
      };
      img.src = url;
    })
  }

  // 将canvas转化成image，才可以进行下载，必须等canvas绘制完成
  function convertCanvasToImage(canvas) {
    let resultImage = document.getElementById("resultImage")
    resultImage.setAttribute("crossOrigin", 'Anonymous'); //跨域在前
    let imgUrL = canvas.toDataURL("image/jpeg");
    resultImage.src = imgUrL
  }
   
  draw()
  
  </script>
</body>
</html>